import 'package:flutterapp/Base/methodChannel/MethodChannelManager.dart';
import 'package:flutterapp/JpushManager.dart';
import 'package:flutterapp/SaasManager.dart';
import 'package:flutterapp/UniqueIDUtil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jmessage_flutter/jmessage_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

class DirectiveManager {
  static const TOAST_MSG = "-1";
  static const DIRECT_LOAD_URI = "1";
  static const DIRECT_OPEN_PKG_NAME = "2";

  static bool verifyDirective(String label, String directiveCode,
      {String directiveArgs = ""}) {
    if (label == null || label == "") {
      Fluttertoast.showToast(msg: "自定义指令名不能为空");
      return false;
    }
    bool res = false;
    switch (directiveCode) {
      case DIRECT_LOAD_URI:
        if (directiveArgs.isEmpty) {
          Fluttertoast.showToast(msg: "uri不能为空");
        } else {
          res = true;
        }
        break;
      case DIRECT_OPEN_PKG_NAME:
        if (directiveArgs.isEmpty) {
          Fluttertoast.showToast(msg: "包名不能为空");
        } else {
          res = true;
        }
        break;

      default:
        Fluttertoast.showToast(msg: "指令不存在");
        break;
    }
    return res;
  }

  static dispatch(JMTextMessage msg) async {
    String idFrom = msg.from.username;
    String code = msg.extras["code"];
    String args = msg.extras["args"];
    print("DirectiveManager dispatch from:$idFrom code：$code args:$args");

    switch (code) {
      case DIRECT_LOAD_URI:
        if (await canLaunch(args)) {
          await launch(args);
          SaasManager.addEvent(
              1, "$idFrom=>${UniqueIDUtil.deviceID} 已加载uri $args");
          JpushManager.sendMsg(
              idFrom, TOAST_MSG, "${UniqueIDUtil.deviceID} 已加载uri $args");
        } else {
          SaasManager.addEvent(
              0, "$idFrom=>${UniqueIDUtil.deviceID} 无法已加载uri $args");
          JpushManager.sendMsg(
              idFrom, TOAST_MSG, "${UniqueIDUtil.deviceID} 无法已加载uri $args");
        }
        break;
      case DIRECT_OPEN_PKG_NAME:
       try {
         await MethodChannelManager.getInstance().invoke(MethodTypes.OPEN_PKG, args);
         SaasManager.addEvent(
             1, "$idFrom=>${UniqueIDUtil.deviceID} 已打开包名 $args");
         JpushManager.sendMsg(
             idFrom, TOAST_MSG, "${UniqueIDUtil.deviceID} 已打开包名 $args");
       } catch (e) {
         SaasManager.addEvent(
             0, "$idFrom=>${UniqueIDUtil.deviceID} 无法打开包名 $args");
         JpushManager.sendMsg(
             idFrom, TOAST_MSG, "${UniqueIDUtil.deviceID} 无法打开包名 $args");
         print(e);
       }
        break;
      case TOAST_MSG:
        Fluttertoast.showToast(msg: args);
        break;
      default:
        SaasManager.addEvent(
            0, "$idFrom=>${UniqueIDUtil.deviceID} 无效的指令码 $code");
        break;
    }
  }
}
